/*eslint-disable */
import axios from 'axios'
import { Loading } from 'element-ui'
// import cookieparser from 'cookieparser'
import Cookie from 'js-cookie'
let loadingInstance
export const ajax = axios.create({
  baseURL: 'https://conduit.productionready.io'
})

export default (context) => {
  // console.log(context.store)
  console.log('plugins')
  // 添加一个请求拦截器
  ajax.interceptors.request.use(
    function(config) {
      if (Loading) {
        loadingInstance = Loading.service({
          fullscreen: true,
          background: 'rgba(0,0,0,.5)',
          text: '正在拼命加载中...'
        })
      }
      let token = null
      if (context.store.state.user && context.store.state.user.token) {
        token = context.store.state.user.token
        config.headers.Authorization = `Token ${token}`
      }

      // let token = Cookie.get('user')
      // if (token) {
      //   token = JSON.parse(token).token
      //   config.headers.Authorization = `Token ${token}`
      // }
      // console.log('ttttt', token)

      // Do something before request is sent
      return config
    },
    function(error) {
      // Do something with request error
      return Promise.reject(error)
    }
  )

  // 添加一个响应拦截器
  ajax.interceptors.response.use(
    function(response) {
      if (Loading && loadingInstance) {
        loadingInstance.close()
      }
      // Do something with response data
      return response
    },
    function(error) {
      if (Loading && loadingInstance) {
        loadingInstance.close()
      }
      // Do something with response error
      return Promise.reject(error)
    }
  )
}
